<?php
/**
 * Plugin Name: DeepSeek2025 Content Generator
 * Plugin URI: https://yourdomain.com/
 * Description: 集成DeepSeek智能内容生成功能的WordPress插件
 * Version: 1.0.0
 * Author: Your Name
 * Author URI: https://yourdomain.com/
 * License: GPL-3.0+
 * License URI: http://www.gnu.org/licenses/gpl-3.0.txt
 * Text Domain: deepseek-gen
 */

// 安全验证
defined('ABSPATH') || exit;

// 定义插件常量
define('DEEPKSEEK_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('DEEPKSEEK_PLUGIN_URL', plugin_dir_url(__FILE__));

// 包含必要库
require_once DEEPKSEEK_PLUGIN_DIR . 'includes/parsedown.php';

class DeepSeek_Content_Generator {

    public function __construct() {
        // 初始化钩子
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('add_meta_boxes', [$this, 'add_meta_box']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        
        // AJAX处理
        add_action('wp_ajax_deepseek_generate', [$this, 'ajax_generate_content']);
        add_action('wp_ajax_deepseek_confirm', [$this, 'ajax_confirm_content']);
    }

    // 注册管理菜单
    public function add_admin_menu() {
        add_menu_page(
            'DeepSeek Settings',
            'DeepSeek设置',
            'manage_options',
            'deepseek-settings',
            [$this, 'settings_page'],
            'dashicons-edit-page'
        );
    }

    // 注册设置项
    public function register_settings() {
        register_setting('deepseek_settings', 'deepseek_api_key');
        register_setting('deepseek_settings', 'default_word_count');
        register_setting('deepseek_settings', 'default_content_type');
        
        add_settings_section(
            'deepseek_main',
            'API设置',
            null,
            'deepseek-settings'
        );

        add_settings_field(
            'deepseek_api_key',
            'API密钥',
            [$this, 'api_key_field'],
            'deepseek-settings',
            'deepseek_main'
        );

        add_settings_field(
            'default_word_count',
            '默认字数',
            [$this, 'word_count_field'],
            'deepseek-settings',
            'deepseek_main'
        );

        add_settings_field(
            'default_content_type',
            '默认文章类型',
            [$this, 'content_type_field'],
            'deepseek-settings',
            'deepseek_main'
        );
    }

    // 添加文章元框
    public function add_meta_box() {
        add_meta_box(
            'deepseek_generator',
            'DeepSeek智能生成',
            [$this, 'meta_box_content'],
            'post',
            'advanced',
            'high'
        );
    }

    // 加载资源文件
    public function enqueue_assets($hook) {
        if ($hook === 'post-new.php' || $hook === 'post.php') {
            wp_enqueue_style(
                'deepseek-admin',
                DEEPKSEEK_PLUGIN_URL . 'assets/admin.css',
                [],
                filemtime(DEEPKSEEK_PLUGIN_DIR . 'assets/admin.css')
            );

            wp_enqueue_script(
                'deepseek-generator',
                DEEPKSEEK_PLUGIN_URL . 'assets/generator.js',
                ['jquery'],
                filemtime(DEEPKSEEK_PLUGIN_DIR . 'assets/generator.js'),
                true
            );

            wp_localize_script('deepseek-generator', 'deepseekVars', [
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('deepseek_nonce')
            ]);
        }
    }

    // AJAX生成内容
  // 修改后的ajax_generate_content方法
public function ajax_generate_content() {
    // 临时调试方法（在ajax_generate_content开始处添加）
    try {
        check_ajax_referer('deepseek_nonce', 'nonce');

        // 记录接收到的参数
        error_log(print_r($_POST, true));

        if (empty($_POST['prompt'])) {
            throw new Exception('提示词不能为空');
        }

        $prompt = sanitize_text_field($_POST['prompt']);
        $content_type = sanitize_text_field($_POST['content_type']);
        $word_count = intval($_POST['word_count']);

        // 验证字数范围
        if ($word_count < 300 || $word_count > 5000) {
            throw new Exception('字数范围应在300-5000之间');
        }

        $response = $this->call_deepseek_api([
            'prompt' => $prompt,
            'content_type' => $content_type,
            'word_count' => $word_count
        ]);

        if (is_wp_error($response)) {
            throw new Exception($response->get_error_message());
        }

        if (empty($response)) {
            throw new Exception('API返回内容为空');
        }

        wp_send_json_success([
            'content' => $response,
            'html' => $this->markdown_to_html($response)
        ]);

    } catch (Exception $e) {
        error_log('DeepSeek Error: ' . $e->getMessage());
        wp_send_json_error($e->getMessage());
    }
}
    // 确认内容处理
    public function ajax_confirm_content() {
        check_ajax_referer('deepseek_nonce', 'nonce');

        $content = wp_kses_post($_POST['content']);
        $html_content = $this->markdown_to_html($content);

        // 提取元数据
        $metadata = $this->extract_metadata($html_content);

        wp_send_json_success([
            'html_content' => $html_content,
            'metadata' => $metadata
        ]);
    }

    // 调用DeepSeek API
 
// 修改后的API调用方法
private function call_deepseek_api($data) {
    $api_key = get_option('deepseek_api_key');
    
    if (empty($api_key)) {
        return new WP_Error('api_error', 'API密钥未配置');
    }

    $api_url = 'https://api.deepseek.com/chat/completions';

    $body = [
        'model' => 'deepseek-chat',
        'messages' => [[
            'role' => 'user',
            'content' => "请生成{$data['content_type']}，要求：{$data['prompt']}，字数约{$data['word_count']}字"
        ]],
        "stream"=>false, 
        // 'temperature' => 0.7,
        // 'max_tokens' => $data['word_count'] * 2
    ];

    error_log('API Request: ' . print_r($body, true));

//  print_r(json_encode($body));
    // exit;
    $response = wp_remote_post($api_url, [
        'timeout' => 600,
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key
        ],
        'body' => json_encode($body)
    ]);
   
    

    if (is_wp_error($response)) {
        error_log('WP HTTP Error: ' . $response->get_error_message());
        return $response;
    }

    $response_code = wp_remote_retrieve_response_code($response);
    $response_body = wp_remote_retrieve_body($response);

    error_log('API Response Code: ' . $response_code);
    error_log('API Response Body: ' . $response_body);

    if ($response_code != 200) {
        return new WP_Error('api_error', "API返回异常状态码：$response_code");
    }

    $decoded = json_decode($response_body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        return new WP_Error('json_error', 'JSON解析失败: ' . json_last_error_msg());
    }

    if (!isset($decoded['choices'][0]['message']['content'])) {
        error_log('Invalid API Response: ' . print_r($decoded, true));
        return new WP_Error('api_error', 'API返回数据结构异常');
    }

    return $decoded['choices'][0]['message']['content'];
}
    // Markdown转HTML
    private function markdown_to_html($content) {
        $parsedown = new Parsedown();
        return $parsedown->text($content);
    }

    // 提取元数据
    private function extract_metadata($content) {
        // 提取标题
        preg_match('/<h1>(.*?)<\/h1>/i', $content, $title_matches);
        $title = $title_matches[1] ?? '';

        // 提取关键词
        preg_match_all('/<strong>(.*?)<\/strong>/', $content, $keywords);
        $keywords = array_slice(array_unique($keywords[1]), 0, 5);

        // 生成描述
        $description = wp_trim_words(strip_tags($content), 30);

        return [
            'title' => $title,
            'keywords' => $keywords,
            'description' => $description
        ];
    }

    // 以下是设置页面相关方法...
    public function settings_page() {
        include DEEPKSEEK_PLUGIN_DIR . 'templates/settings.php';
    }

    public function api_key_field() {
        $value = get_option('deepseek_api_key');
        echo '<input type="password" name="deepseek_api_key" value="'.esc_attr($value).'" class="regular-text">';
    }

    public function word_count_field() {
        $value = get_option('default_word_count', 1000);
        echo '<input type="number" name="default_word_count" value="'.esc_attr($value).'" min="300" max="5000">';
    }

    public function content_type_field() {
        $value = get_option('default_content_type', 'blog_post');
        $options = [
            'blog_post' => '博客文章',
            'news' => '新闻稿',
            'product_desc' => '产品描述'
        ];
        
        echo '<select name="default_content_type">';
        foreach ($options as $key => $label) {
            echo '<option value="'.esc_attr($key).'" '.selected($value, $key, false).'>'.esc_html($label).'</option>';
        }
        echo '</select>';
    }

    // 元框内容
    public function meta_box_content($post) {
        include DEEPKSEEK_PLUGIN_DIR . 'templates/meta-box.php';
    }
}

new DeepSeek_Content_Generator();